package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.dto.LoginDTO;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.util.RedisUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisUtil redisUtil;

    private static final String TOKEN_PREFIX = "user:token:";
    private static final long TOKEN_EXPIRE_TIME = 24; // token过期时间（小时）

    @Override
    public Result<LoginDTO> login(String loginName, String password) {
        try {
            // 对密码进行MD5加密
            String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            
            // 查询用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getLoginName, loginName)
                   .eq(User::getPassword, encryptedPassword);
            
            User user = this.getOne(wrapper);
            if (user != null) {
                // 生成token
                String token = generateToken();
                
                // 将用户信息存入Redis
                String redisKey = TOKEN_PREFIX + token;
                redisUtil.set(redisKey, user, TOKEN_EXPIRE_TIME, TimeUnit.HOURS);
                
                // 构建返回对象
                LoginDTO loginDTO = new LoginDTO();
                loginDTO.setLoginName(user.getLoginName());
                loginDTO.setToken(token);
                
                return Result.success(loginDTO, "登录成功");
            } else {
                return Result.businessError("用户名或密码错误");
            }
        } catch (Exception e) {
            return Result.serverError("登录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Void> logout(String token) {
        try {
            // 删除Redis中的token
            String redisKey = TOKEN_PREFIX + token;
            redisUtil.delete(redisKey);
            return Result.success(null, "登出成功");
        } catch (Exception e) {
            return Result.serverError("登出失败：" + e.getMessage());
        }
    }

    /**
     * 生成token
     * @return token字符串
     */
    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
} 